import pymysql


# 数据库操作模块
# 封装一个数据库操作类 DB
# 读方法 read(sql) return 受影响行数,结果集
# 写方法 write(sql) return 受影响行数


class DB:
    def __init__(self, database, host='localhost', user='root', password='root', port=3306, charset='utf8',
                 cursor_type=pymysql.cursors.Cursor):
        # 初始化连接对象
        # 设置为私有属性,对象属性
        self.__conn = pymysql.connect(host=host, user=user, password=password, port=port, charset=charset,
                                      database=database)
        # 初始化游标对象
        # 游标类型:元组,字典
        self.__cursor = self.__conn.cursor(cursor_type)

    def __del__(self):
        # 对象销毁后执行的方法
        self.__cursor.close()
        self.__conn.close()

    def read(self, sql, params_list=None):
        # 执行sql语句
        # 获取结果集
        if params_list is None:
            params_list = []
        try:
            rows = self.__cursor.execute(sql, params_list)
            data = self.__cursor.fetchall()
        except Exception as e:
            print('sql语句有问题')
            return None, 'No data'
        return rows, data

    def write(self, sql, params_list=None):
        # 执行sql语句
        if params_list is None:
            params_list = []
        try:
            rows = self.__cursor.execute(sql, params_list)
        except Exception as e:
            # 回滚
            self.__conn.rollback()
            return 0
        else:
            # 提交
            self.__conn.commit()
        return rows


if __name__ == '__main__':
    db = DB('advanced')
    name = input('姓名:')
    print(db.read(f"select * from student where stu_name = %s"))


